import React, { useState ,useEffect ,useRef } from 'react';
import {
ModalForm, ProFormText, ProFormTextArea,ProFormSelect,ProFormRadio,ProFormCheckbox,ProFormDatePicker } from '@ant-design/pro-form';
import { Editor } from '@tinymce/tinymce-react';
import { UploadOutlined,FileOutlined,DeleteOutlined } from '@ant-design/icons';
import { Form ,Modal,Button,Upload,message} from 'antd';
import { useIntl, FormattedMessage } from 'umi';

import type { TableListItem } from '../data.d';
import { upload } from '../../../common/upload/service';
  import { findDictionaryList } from '../../../system/dictionary/service';

export type FormValueType = {} & Partial<TableListItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [form] = Form.useForm();
  const [introFiles, setintroFiles] = useState<any>([]);
  const [contentData, setcontentData] = useState<any>([]);
  const [read_numData, setread_numData] = useState<any>([]);

  useEffect(() => {
    if (form && !props.updateModalVisible) {
      form.resetFields();
    }
    setintroFiles(props.values?.introFileList||[])
    findDictionaryList({parent_code:'fl1001'}).then((response) => {
    let data = [];
    for(var i=0;i<response.data?.length||0;i++){
      data.push({label:response.data[i].name,value:response.data[i].id});
    }
    setcontentData(data);
    })
    const options = [
      '北京',
      '上海',
      '深圳',
    ];
    setread_numData(options);
  }, [props.updateModalVisible]);

  const intl = useIntl();
  let index = 0;
  const handleOk = () => {
    form.submit();
    if(index>0){
      props.onCancel()
    }
    index++;
  };
  const handleCancel = () => {
    props.onCancel()
  }
  const handleFinish = (values: Record<string, any>) => {
        values.intro = introFiles.map((item:any) => item.id).join(',')
      props.onSubmit(values as FormValueType);
  };

    const uploadintroFile = async (file: any) => {
      const formData = new FormData();
      formData.append("file", file.file);
      await upload(formData).then(res => {
        console.log('上传完毕11---');
        console.log(res);
        console.log(introFiles.concat(res.data))
        setintroFiles(introFiles.concat(res.data));
      })
    }
    const handleintroUploadChange = async (info: any) => {
      if (info.file.status === 'uploading') {
        return;
      }
      if (info.file.status === 'done') {
        console.log('上传完毕---');
        console.log(info);
      }
    }

    const removeintroFile = async (item: any) => {
      let data = introFiles.filter((ele:any) => ele.id !== item.id)
      setintroFiles(data);
      message.success('删除成功');
      console.log(data)
    }

  return (
    <Modal
      width={640}
      title={intl.formatMessage({
        id: '编辑',
        defaultMessage: '编辑',
      })}
      visible={props.updateModalVisible}
      destroyOnClose
      onOk={handleOk} onCancel={handleCancel}
    >
      <Form
        form={form} 
        onFinish={handleFinish}
        initialValues={props.values}
      >

        <ProFormTextArea width="xl"
          rules={[
            {
              required: true,
              message: '标题',
            },
          ]}
          name="title"
          label='标题'
          placeholder="请输入标题" />


            <Form.Item label="附件上传" name="requiredMarkValue">
              <Upload
                name="file"
                showUploadList={false}
                customRequest={uploadintroFile}
                onChange={handleintroUploadChange}
              >
                <Button><UploadOutlined /> 上传 </Button>
              </Upload>
              <div>
                {
                  introFiles.map((item: any) => {
                    return <div id={'div_'+item.id} style={{ lineHeight: '30px' }}>
                      <a onClick={() => {
                      window.location.href =
                      "../api/system/upload/downloadFile?name=" +
                      item.name +
                      "&file_path=" +
                      item.file_path;
                      }}><FileOutlined />{item.name}</a>
                      <a onClick={() => {
                        removeintroFile(item)
                      }} style={{ paddingLeft: '10px', color: 'red' }}><DeleteOutlined /></a>
                  </div>
                })
              }
              </div>
            </Form.Item>

        <ProFormSelect width="xl"
          options={contentData}
          name="content"
          label='内容'
          placeholder="请选择内容" />

        <ProFormRadio.Group width="xl"
          options={read_numData}
          name="read_num"
          label='阅读数量'
          placeholder="请选择阅读数量" />

          <ProFormDatePicker width="xl"
            name="order_by"
            label='排序'
            placeholder="请输入排序" />
        <ProFormTextArea width="xl"
          name="remark"
          label='备注'
          placeholder="请输入备注" />

        </Form>
    </Modal>    
  );
};

export default UpdateForm;
